﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using AMS.DataAccess.Sql;
using AMS.DataAccess.BO;
using AMS.DataAccess.Interfaces;
using AMS.DataAccess.BO.Enums;
using AMS.DataAccess.Validators;

public partial class Customer_EditCustomer : BaseWorkPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Anthem.Manager.Register(this);

        if (!ParseStringParameter("op", out currentAction))
        {
            GlobalTransfer.RedirectToErrorPage("Paremeter not found.");
            return;
        }

        if (!ValidateParameter<string>(currentAction, new string[]{"add", "edit"}))
        {
            GlobalTransfer.RedirectToErrorPage("Paremeter invalid.");
            return;
        }

        if (currentAction == "edit")
        {
            if (!ParseIntParameter("id", out itemId))
            {
                GlobalTransfer.RedirectToErrorPage("Paremeter not found.");
                return;
            }
        }
        else
        {
            txtTitle.Text = "添加客户";
            btnContactor.Visible = false;
            btnContactorFile.Visible = false;
        }

        if (!IsPostBack)
        {
            BindDropdownLists();
            btnContactor.OnClientClick = string.Format(ConcatorScript, 0);
            if (currentAction == "edit")
            {
                DoDataBind();
            }
        }
    }

    #region Private Fields
    string ConcatorScript = "window.location.href='ManageCustomerContactor.aspx?id={0}';return false;";
    int itemId;
    string currentAction;
    #endregion

    #region DataBind
    void BindDropdownLists()
    {
        IProvinceCityManager pc = ManagerFactory.CreateProvinceManager();
        List<ProvinceCityInfo> provinces = pc.GetProvinces(CallContext);
        drpProvince.DataSource = provinces;
        drpProvince.DataTextField = "ProvinceName";
        drpProvince.DataValueField = "ProvinceID";
        drpProvince.DataBind();

        if (drpProvince.Items.Count > 0)
        {
            BindCities(drpProvince.Items[0].Value);
        }
    }

    void DoDataBind()
    {
        CustomerInfo customer = GetCustomerInfo();
        if (customer != null)
        {
            txtName.Text = customer.Name;
            txtName_En.Text = customer.Name_En;
            txtCustomerCode.Text = customer.IDCode;
            drpBusinessType.SelectedValue = ((int)customer.BusinessType).ToString();
            drpCustomerType.SelectedValue = ((int)customer.CustomerType).ToString();
            drpCountry.Text = customer.CountryID;
            drpProvince.Text = customer.ProvinceId;
            BindCities(customer.ProvinceId);
            drpCity.Text = customer.CityId;
            txtAddress.Text = customer.Address;
            txtZipCode.Text = customer.ZipCode;
            txtHomepage.Text = customer.HomePage;

            if (customer.Contactors != null && customer.Contactors.Count > 0)
            {
                ContactorInfo contactor = customer.Contactors[0];

                txtContactorName.Text = contactor.Name;
                txtContactorAddress.Text = contactor.Address;
                txtContactorFax.Text = contactor.Fax;
                txtContactorZipcode.Text = contactor.Zipcode;
            }
        }
        else
        {
            MsgWarning("客户不存在。");
            Response.End();
        }
    }

    CustomerInfo GetCustomerInfo()
    {
        ICustomerManager customerMgr = ManagerFactory.CreateCustomerManager();
        CustomerInfo customer = customerMgr.GetCustomer(itemId);
        if (customer != null)
        {
            IContactorManager contactorManager = ManagerFactory.CreateContactorManager();
            ContactorInfo contactor = contactorManager.GetCustomerFirstContactor(CallContext, itemId);
            if (contactor != null)
            {
                List<ContactorInfo> list = new List<ContactorInfo>();
                list.Add(contactor);
                customer.Contactors = list;
            }
        }

        return customer;
    }
    #endregion

    #region Drop down list
    protected void drpCountry_DataBound(object sender, EventArgs e)
    {
        if (drpCountry.Items.Count > 0)
        {
            try
            {
                drpCountry.SelectedValue = Constants.ChinaCountryID;
            }
            catch (Exception)
            {
                drpCountry.SelectedIndex = 0;
            }
        }
    }

    /// <summary>
    /// bind city
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void drpProvince_DataBound(object sender, EventArgs e)
    {
        if (drpProvince.Items.Count > 0)
        {
            BindCities(drpProvince.SelectedValue);
        }
    }

    private void BindCities(string provinceId)
    {
        IProvinceCityManager mgr = ManagerFactory.CreateProvinceManager();
        List<ProvinceCityInfo> cities = mgr.GetCitiesByProvince(CallContext, provinceId);
        if (cities.Count == 0)
        {
            cities.Add(new ProvinceCityInfo(drpProvince.SelectedValue, drpProvince.Text));
        }

        drpCity.DataSource = cities;
        drpCity.DataTextField = ProvinceCityInfo.NameFieldName;
        drpCity.DataValueField = ProvinceCityInfo.IDFieldName;
        drpCity.DataBind();
    }
    #endregion

    private void RetriveCustomerInfo(CustomerInfo customer)
    {
        customer.Address = txtAddress.Text;
        customer.BusinessType = (CustomerBusinessType)int.Parse(drpBusinessType.SelectedValue);
        customer.CityId = drpCity.SelectedValue;
        customer.CountryID = drpCountry.SelectedValue;
        //customer.CreditLevel = drp
        customer.CustomerType = (CustomerType)int.Parse(drpCustomerType.SelectedValue);
        customer.HomePage = txtHomepage.Text;
        customer.IDCode= txtCustomerCode.Text;
        customer.Name = txtName.Text;
        customer.Name_En = txtName_En.Text;
        //customer.Note = edt
        customer.ProvinceId = drpProvince.SelectedValue;
        customer.Represent = txtRepresenter.Text;
        customer.RepresentPosition = txtRepresenterPosition.Text;
        //customer.SpecialNeeds = txts
        customer.Tel = txtTel.Text;
        customer.ZipCode = txtZipCode.Text;
    }

    private void RetriveFirstContactor(ContactorInfo contactor)
    {
        // TODO: ADD OTHER ITEMS
        contactor.Name = txtContactorName.Text;
        contactor.Address = txtContactorAddress.Text;
        //contactor.Birthday = txt
        contactor.Tel = txtTel.Text;
        contactor.Fax = txtContactorFax.Text;
        contactor.Mobile = txtMobile.Text;
        contactor.Zipcode = txtContactorZipcode.Text;
        contactor.Sex = "0";
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        ICustomerManager customerMgr = ManagerFactory.CreateCustomerManager();
        IContactorManager contactorMgr = ManagerFactory.CreateContactorManager();
        IList<ContactorInfo> contactors = new List<ContactorInfo>();

        CustomerInfo customer = new CustomerInfo();
        ContactorInfo contactor =new ContactorInfo();
        RetriveCustomerInfo(customer);
        RetriveFirstContactor(contactor);
        contactor.CustomerID = customer.AID;
        contactors.Add(contactor);
        customer.Contactors = contactors;

        // TODO: validate customer
        CustomerValidator customerValidator = new CustomerValidator();
        bool validateResult = customerValidator.Validate(customer);
        if (!validateResult)
        {
            MsgError(customerValidator.ErrorMessage);
            return;
        }

        if (currentAction == "edit")
        {
            customer.AID = itemId;
            // TODO: save customer and contactors
            customerMgr.UpdateCustomer(CallContext, customer);
            if (customer.Contactors.Count > 0)
            {
                contactorMgr.UpdateContactors(CallContext, customer.Contactors);
            }

            MsgInfo("编辑客户成功。");
        }
        else
        {
            customer.CreateUser = CallContext.UserName;
            // TODO: save customer and contactors
            int newId = customerMgr.AddCustomer(CallContext, customer);
            customer.AID = newId;
            foreach (ContactorInfo con in customer.Contactors)
            {
                con.CustomerID = customer.AID;
            }

            if (customer.Contactors != null || customer.Contactors.Count > 0)
            {
                contactorMgr.AddContactors(CallContext, customer.Contactors);
            }

            MsgInfo("添加客户成功。");
            //Response.Redirect("AllCustomers.aspx");
        }
    }

    protected void drpProvince_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindCities(drpProvince.SelectedValue);
    }
}
